<?php

class WP_Solr_Metabox {
	
	/**
	 * The id of this meta box
	 * @var string
	 */
	const ID = 'wp-solr-meta';
	
	/**
	 * Bootstrap class
	 * Initialization of the meta post section
	 *
	 * @access	public
	 * @static
	 */
	public static function bootstrap() {
		add_action( 'save_post', array(__CLASS__, 'save_post'), 1, 2 );
		self::register_meta_box();
	}
	
	///////////////////////////////////////////////////////////////////////////////
	
	public static function save_post($post_id, $post) {

		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) { 
			return;
		}

		if ( !wp_verify_nonce( $_POST[WP_Solr::SLUG . '_nounce'], WP_Solr::$plugin_path ) ) {
			return;
		}

		if ( $post->post_type == 'page' ) {
			if ( !current_user_can( 'edit_page', $post_id ) ) {
				return;
			}
		} else {
			if ( !current_user_can( 'edit_post', $post_id ) ) {
				return;
			}
		}

		update_post_meta($post_id, WP_Solr::META_INDEX, filter_var($_POST['wp_solr_index'], FILTER_VALIDATE_BOOLEAN));
		
	}
	
	///////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Register post meta
	 */
	public static function register_meta_box() {
		$options = WP_Solr::get_cached_options();
		if ( !empty($options) && !empty($options[WP_Solr_Admin::SAVE_OR_EDIT_TYPES]) ) {
			foreach ( $options[WP_Solr_Admin::SAVE_OR_EDIT_TYPES] as $type ) {
				add_meta_box (
					$id = self::ID, 
					$title = __('Search Results', WP_Solr::TEXT_DOMAIN), 
					$callback = array(__CLASS__, 'render_meta_box'), 
					$page = $type, 
					$context = 'advanced', 
					$priority = 'default'
				);
			}
		}
	}
	
	///////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Renders the meta box
	 */
	public static function render_meta_box() {
		include WP_Solr::$plugin_path . '/views/view-metabox.php';
	}
	
}
?>